package com.my.ph.controller;

import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint("/websocket/{userId}")
@Slf4j
public class WebSocketServer {

    private static final ConcurrentHashMap<String, Session> WEB_SOCKET_MAP = new ConcurrentHashMap<>();

    private String userId;

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId){
        this.userId = userId;
        WEB_SOCKET_MAP.put(userId, session);
    }
    @OnClose
    public void onClose(){
        WEB_SOCKET_MAP.remove(userId);
    }

    @OnMessage
    public void onMessage(String message,Session session){

    }

    private void sendMessageTo(String userId, String obj){
        Session curSession = WEB_SOCKET_MAP.get(userId);
        try {
            if(curSession !=null){
                curSession.getAsyncRemote().sendText(obj);
            }
        } catch (Exception e) {
            log.error("服务端发送消息给{}失败:{}", userId, e.getMessage(), e);
            log.error("{}", e.getMessage(), e);
        }
    }


    private void sendMessageToAll(String message){
        for (Map.Entry<String, Session> client : WEB_SOCKET_MAP.entrySet()) {
            Session toSession = client.getValue();
            if(toSession.isOpen()){
                toSession.getAsyncRemote().sendText(message);
                log.info("服务端发送消息给{} : {}", client.getKey(), message);
            }
        }
    }

}
